<?php

/**
*
* @author: Korowanire
* @description: Base class for greatest database lulz and Dragon's glory
*/

require_once "inc/database.class.php";

abstract class Base{

	public $data = array();
	public $tableName = null;
	public $idValue = null;
	public static $tableInfo = false;	
	
	protected $dbh = null;
	
	public function Base() {
		$this->dbh = new DBConnector();
	}
		
	public function load($idValue, $idName = false)
	{
		
		if($this->getTableName() == null) throw new Exception("It is base class.");  // if base class then fuck by niggerz
		$idName = $idName ? $idName : get_class() . "_id";
		$this->idValue = $idValue ? $idValue : $this->idValue;
		//echo $idValue, $idName;
		//echo "SELECT * FROM ".$this->getTableName()." WHERE ".mysql_escape_string($idName)."='".mysql_escape_string($this->idValue)."'";
		$q = $this->dbh->query("SELECT * FROM ".$this->getTableName()." WHERE ".$this->dbh->escape($idName)."='".$this->dbh->escape($this->idValue)."'");
	
		if($this->dbh->error()) throw new Exception($this->dbh->error());
		$this->data = mysql_fetch_assoc($q);
		//print_r($this->data);
		
		if(!$this->data) throw new Exception("Have no data '{$name}' in class '".__CLASS__."' and method '".__FUNCTION__."' and value {$idValue} and field {$idName}");
	
	}
	
	public function getClass()
	{
		return get_class($this);
	}
	
	public function getTableName()
	{
		if($this->getClass() == "Base") return null;
		return strtolower($this->getClass()."s");
	}
		
	public function __get($name)
	{
		if(isset($this->data[$name])){return $this->data[$name];}
			else{throw new Exception("Cannot find field '{$name}' in class '".__CLASS__."' and method '".__FUNCTION__."'");}
	}
	
	public function __set($name, $value)
	{
		if(isset($this->data[$name])){$this->data[$name] = $value;}
		else $this->$name = $value;
	}
	
	
	public function loadTableInfo()
	{
		if(isset(self::$tableInfo[$this->getTableName()]))return;
		if(!self::$tableInfo) self::$tableInfo = array();
		$class = $this->getTableName();
		self::$tableInfo[$class] = array();
		$tblclass = create_function('', 'class TableDefiner extends DBIterator {
			public $arrOut;
			public function iterate($row) {
				$this->arrOut[] = $row["Field"];
			}
			public function getData() {
				return $this->arrOut;
			}
		};
		return new TableDefiner();');
		$tbldef = $tblclass();		
		$q = $this->dbh->result("describe ".$this->getTableName()."", $tbldef);
		self::$tableInfo[$class] = $q->getData();
		//print_r(self::$tableInfo[$class]);		
		/*while($r = mysql_fetch_assoc($q))
		{
			self::$tableInfo[$class][] = $r['Field'];
		}*/
	}
	
	public function save($idName = "id", $isUpdate = false)
	{
		$this->loadTableInfo();
		$table = $this->getTableName();
		$is_exist = false;
		try {
			$is_exist = $this->dbh->count($table, $this->dbh->escape($idName)."='".$this->dbh->escape($this->$idName)."'") > 0;
		} catch (Exception $e) {
			
		}		
		if ($is_exist && !$isUpdate) {
			throw new Exception('Duplicate not allowed');
		}
		$query = "";
		if($is_exist)
		{
			$query = "UPDATE {$table} SET ";
			$pieces = array();
			foreach(self::$tableInfo[$table] as $value)
			{
				try{
					$pieces[] = $value . "="."'".$this->dbh->escape($this->$value)."'";
				}
				catch(Exception $e){
					//throw new Exception("Cannot save because field {$value} is not set.");
				}
			}
			$query .= implode(",",$pieces)." where {$idName}='".$this->dbh->escape($this->$idName)."'";
		}
		else
		{
			$query = "insert into {$table} ";
			$fields = array();
			$values = array();
			foreach(self::$tableInfo[$table] as $value)
			{
				try {					
					$values[] = "'".$this->dbh->escape($this->$value)."'";
					$fields[] = $value;
				}
				catch(Exception $e){
					//throw new Exception("Cannot save because field {$value} is not set.");				
				}
			}
			$query .= "(".implode(",",$fields).") values (".implode(",",$values).")";
		}
		//print_r($query);
		$this->dbh->query($query);
	}
	
	public static function massload($class, $cond)
	{
		$q = $this->dbh->query("select * from {$class}s where {$cond}");
		if($this->dbh->error())throw new Exception("Query error in {$cond}");
		$strokes = array();
		while($r = mysql_fetch_array($q))
		{
			$obj = new $class;
			$obj->data = $r;
			$strokes[] = $obj;
		}
		
		return $strokes;
	}
	
}



// loading by condition
// loading several objects (static method)

